import axios from 'axios'
import config from '@/config/'
import {
    Message
} from 'element-ui'
import {
    getStore
} from "../common";
import {
    closeLoading
} from "@/common/prompt";
const baseURL = config.urlConfig.baseURL;
let showError = true;

const service = axios.create({
    baseURL,
    timeout: 60000, // 请求超时时间
    crossDomain: true, //设置cross跨域
    withCredentials: true //设置cross跨域 并设置访问权限 允许跨域携带cookie信息
});

// request拦截器
service.interceptors.request.use(config => {
    config.headers['Content-Type'] = "application/json;charset=utf-8";
    config.headers.common['Token'] = getStore('token');
    return config
}, error => {
    Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
    response => {
        closeLoading();
        return response
    },
    error => {
        closeLoading();
        if (error.response && error.response.status == 403) {
            Message.error({
                message: "您未有权限使用。"
            });
            location.href = '/';
            return;
        }
        if (error.response && showError) {
            showError = false;
            Message.error({
                message: error.response.data.error.message
            });
            setTimeout(() => {
                showError = true;
            }, 5000);
        }
        return Promise.reject(error)
    }
)

export default service;